<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { App } from '../../bindings/generate-iot-cmd'
// import {Events} from "@wailsio/runtime";

const props = defineProps({
  padding: {
    type: Number,
    default: 20
  },
  maxWidth: Number,
  maxHeight: Number
})

const container = ref(null)
let observer = null
let isUserResizing = ref(false)
let debounceTimer = null

// 核心尺寸计算方法
const calculateSize = () => {
  if (!container.value || isUserResizing.value) return

  const rect = container.value.getBoundingClientRect()
  let targetWidth = rect.width + props.padding * 2
  let targetHeight = rect.height + props.padding * 2

  // 应用最大尺寸限制
  if (props.maxWidth && targetWidth > props.maxWidth) {
    targetWidth = props.maxWidth
  }
  if (props.maxHeight && targetHeight > props.maxHeight) {
    targetHeight = props.maxHeight
  }

  console.log('计算后的尺寸:', targetWidth, targetHeight)

  App.ResizeWindow(Math.ceil(targetWidth + 40), Math.ceil(targetHeight + 40))
}

// 防抖优化
const debouncedCalculate = () => {
  clearTimeout(debounceTimer)
  debounceTimer = setTimeout(calculateSize, 100)
}

onMounted(() => {
  // 初始计算
  debouncedCalculate()
  
  // 监听内容变化
  observer = new MutationObserver(debouncedCalculate)
  observer.observe(container.value, {
    childList: true,
    subtree: true,
    attributes: true,
    characterData: true
  })

  // 监听窗口变化
  window.addEventListener('resize', debouncedCalculate)
})

onUnmounted(() => {
  observer?.disconnect()
  window.removeEventListener('resize', debouncedCalculate)
})
</script>

<template>
  <div ref="container" class="resizable-container">
    <slot />
  </div>
</template>

<style scoped>
.resizable-container {
  padding: v-bind('padding + "px"');
  overflow: hidden; /* 关键：防止滚动条影响尺寸计算 */
  min-width: min-content; /* 确保容器收缩到内容宽度 */
}
</style>